<template>
  <div class="applyhome">
    <ContentBox title="申请入驻" @left="back" :fixed="true" :ostyle="style">
      <template slot="oleft"><van-icon color="#000000" name="arrow-left"/></template>
    </ContentBox>
    <notice :top="$remToPx('0.88')"></notice>
    <div v-if="showLoad">
      <div v-if="showView" class="main">
        <div class="from detail">
          <h3 class="title">基本信息</h3>
          <div class="options">
            <van-cell-group>
              <van-field v-model="form.name" label="*商户名称" placeholder="请填写商户名称" />
            </van-cell-group>
            <van-field
              readonly
              clickable
              label="*主营类目"
              :value="value"
              placeholder="请选择主营类目"
              @click="showPicker = true"
            />
              <van-popup v-model="showPicker" position="bottom">
                <van-picker
                  show-toolbar
                  :columns="columns"
                  @cancel="showPicker = false"
                  @confirm="onConfirm"
                />
              </van-popup>
            <van-cell-group>
              <van-field v-model="form.contact" label="*联系人" placeholder="请填写联系人姓名" />
            </van-cell-group>
            <van-cell-group>
              <van-field v-model="form.phone" label="*联系电话" placeholder="请填写联系电话" />
            </van-cell-group>
            <van-cell-group>
              <van-field v-model="areaText" label="*选择地区" placeholder="请选择地区" @click="getShowStatus"/>
            </van-cell-group>
            <van-cell-group>
              <van-field v-model="form.address" label="*详细地址" rows="1" type="textarea" autosize placeholder="请填写商户详细地址" />
            </van-cell-group>
          </div>
        </div>
        <div class="list types">
          <h3 class="title public">*商户头像</h3>
          <div class="shop-avater">
            <van-uploader
              v-model="fileList"
              preview-size="136px"
              multiple
              :max-count="1"
              accept="image/*"
              :after-read="uploadfile"
              :before-read="beforeUploadSetKeysLogo"
            />
          </div>
          <p class="txt">
            logo尺寸推荐144*144,最大不超过1MB
          </p>
          <div class="hr"></div>
          <h3 class="intro public">*商户简介</h3>
          <van-cell-group class="shop_introduction">
            <van-field
              v-model="form.intro"
              autosize
              rows="1"
              type="textarea"
              maxlength="250"
              show-word-limit
              placeholder="请输入商户的简略描述..."
            />
          </van-cell-group>
        </div>
      </div>

      <div v-else class="apply">
        <div class="from">
          <h3 class="title">身份信息</h3>
        </div>
        <div class="types content">
          <div class="clear id_card">
            <div class="fl contcat">
              <h3 class="title-types">身份证人像面</h3>
              <p @click="preview($img('sfzzm.jpg'))">示例</p>
            </div>
            <div class="fl context">
              <van-uploader
                v-model="fileCard"
                :max-count="1"
                class="pic"
                :style="{backgroundImage: `url(${$img('id_card.png')})`}"
                :after-read="uploadfile"
                :before-read="beforeUploadSetKeysIdcardFront"
              >
                <van-button type="default" class="btn" :style="{backgroundImage: `url(${$img('img-bg.png')})`}"></van-button>
              </van-uploader>
            </div>
          </div>
          <div class="clear id_card">
            <div class="fl contcat">
              <h3 class="title-types">身份证国徽面</h3>
              <p @click="preview($img('sfzbm.jpg'))">示例</p>
            </div>
            <div class="fl context">
              <van-uploader
                v-model="fileCard2"
                :max-count="1"
                class="pic"
                :style="{backgroundImage: `url(${$img('id_card2.png')})`}"
                :after-read="uploadfile"
                :before-read="beforeUploadSetKeysIdcardBack"
              >
                <van-button type="default" class="btn" :style="{backgroundImage: `url(${$img('img-bg.png')})`}"></van-button>
              </van-uploader>
            </div>
          </div>
          <div class="clear id_card">
            <div class="fl contcat">
              <h3 class="title-types">手持身份证照</h3>
              <p @click="preview($img('scsfz.jpg'))">示例</p>
            </div>
            <div class="fl context">
              <van-uploader
                v-model="fileCard3"
                :max-count="1"
                class="pic"
                :style="{backgroundImage: `url(${$img('id_card3.png')})`}"
                :after-read="uploadfile"
                :before-read="beforeUploadSetKeysHandIdcard"
              >
                <van-button type="default" class="btn" :style="{backgroundImage: `url(${$img('img-bg.png')})`}"></van-button>
              </van-uploader>
            </div>
          </div>
          <div class="clear id_card">
            <div class="fl contcat">
              <h3 class="title-types">营业执照</h3>
              <p @click="preview($img('yyzz.jpg'))">示例</p>
            </div>
            <div class="fl context">
              <van-uploader
                v-model="fileCard4"
                :max-count="1"
                class="pic"
                :style="{backgroundImage: `url(${$img('id_card3.png')})`}"
                :after-read="uploadfile"
                :before-read="beforeUploadSetKeysLicense"
              >
                <van-button type="default" class="btn" :style="{backgroundImage: `url(${$img('img-bg.png')})`}"></van-button>
              </van-uploader>
            </div>
          </div>
          <div class="clear id_card" v-if="0">
            <div class="fl contcat">
              <h3 class="title-types">核验书</h3>
              <p @click="preview($img('syd_ok.png'))">示例</p>
            </div>
            <div class="fl context">
              <van-uploader
                v-model="fileCard5"
                :max-count="1"
                class="pic"
                :style="{backgroundImage: `url(${$img('id_card3.png')})`}"
                :after-read="uploadfile"
                :before-read="beforeUploadSetKeysCheckBook"
              >
                <van-button type="default" class="btn" :style="{backgroundImage: `url(${$img('img-bg.png')})`}"></van-button>
              </van-uploader>
            </div>
            <div v-if="isApp" class="fl downthis" @click="download">点击下载</div>
            <div v-else class="fl downthis" @click="preview($img('syd.png'))">查看图片</div>
          </div>
        </div>
        <p class="deal">提交资料且代表同意<span @click="toRule('merchant')">《会员申请协议》</span>和<span @click="toRule('privacy_policy')">《隐私政策》</span></p>
      </div>

      <div class="ensure" @click="overNext" v-if="showView">下一步(1/2)</div>
      <div class="ensure" @click="apply" v-if="!showView">提交申请</div>

      <div class="address">
        <van-area
          :area-list="areaList"
          :columns-num="3"
          :columns-placeholder="['请选择', '请选择', '请选择']"
          v-if="showStatus"
          @confirm="save"
          @cancel="cancel"
        />
      </div>
    </div>
    <div v-else class="queit">
      <img :src="$img('apply-status1.png')" v-if="authStatus == 1">
      <img :src="$img('apply-status2.png')" v-if="authStatus == 2">
      <p class="text" v-if="authStatus == 0">您的资料已提交成功，请等待后台审核<br /><span v-if="is_pay === 0">请及时付款以免影响后台审核</span></p>
      <p class="text" v-if="authStatus == 1">您的资料已通过后台审核，成为入驻商家。</p>
      <p class="text" v-if="authStatus == 2">您的资料未通过后台审核，请重新填写资料。</p>
      <div class="select">
        <button class="back" @click="backHome">返回首页</button>
        <button class="quck" v-if="authStatus == 0 && is_pay === 0" @click="toPay">付款</button>
        <button class="quck" v-if="authStatus == 2" @click="showLoad = true">再次认证</button>
      </div>
    </div>
    <van-overlay :show="show" class="loading">
      <van-loading size="2.4rem" :vertical="true"></van-loading>
    </van-overlay>
    <van-image-preview
      v-model="previewShow"
      :images="previewimg"
    >
      <template v-if="previewimg.length > 0 && previewimg[0].indexOf('syd.') > -1" v-slot:index>查看并保存</template>
    </van-image-preview>
  </div>
</template>

<script>
import area from '@/assets/js/area.js'
export default {
  data () {
    return {
      style: {
        background: '#ffffff',
        color: '#000'
      },
      type: 'audit',
      fileList: [],
      fileCard: [],
      fileCard2: [],
      fileCard3: [],
      fileCard4: [],
      fileCard5: [],
      areaList: [],
      form: {
        name: '',
        contact: '',
        phone: '',
        city: '',
        address: '',
        intro: '',
        category: '',
        logo: '',
        province: '',
        country: '',
        idcard_front: '',
        idcard_back: '',
        hand_idcard: '',
        license: ''
      },
      showStatus: false,
      showView: true,
      showLoad: true,
      columns: [],
      showPicker: false,
      value: '',
      areaText: '',
      keys: '',
      show: false,
      formKeys: '',
      allow: 0,
      authStatus: '',
      previewShow: false,
      previewimg: [],
      isApp: false,
      is_pay: false,
      orderid: '',
      total_price: ''
    }
  },
  methods: {
    back () {
      if (this.showView) {
        if (this.$store.state.pl === 'IOS') {
          window.iosCallHandler('popVC')
        } else if (this.$store.state.pl === 'H5') {
          this.$router.go(-1)
        } else if (this.$store.state.pl === 'ANDROID') {
          AndroidJsBridge.finish()
        }
      } else {
        this.showView = true
      }
    },
    getShowStatus () {
      this.showStatus = true
    },
    save (value) {
      this.form.province = value[0].name
      this.form.city = value[1] ? value[1].name : ''
      this.form.country = value[2] ? value[2].name : ''
      this.areaText = `${this.form.province}${this.form.city}${this.form.country}`
      this.showStatus = false
    },
    cancel () {
      this.showStatus = false
    },
    overNext () {
      this.showView = false
    },
    apply () {
      Object.keys(this.form).forEach(key => {
        if (key !== 'hand_idcard' && key !== 'license') {
          if (this.form[key] === '') {
            this.$dialog({ message: '请把表单填写完整' })
            this.allow++
          }
        }
      })
      if (this.allow > 0) {
        return
      }
      if (!/^[1][3,4,5,7,8,9][0-9]{9}$/.test(this.form.phone)) {
        this.$dialog({ message: '手机格式不正确' })
        return
      }
      this.show = true
      this.$axios.post('/api/user/merchant', this.form).then(res => {
        if (res.status === 200) {
          this.showLoad = false
          this.$router.push(`/CreateOrder?wxid=${res.data.order_id}&price=${res.data.price}`)
          this.authStatus = 0
        } else {
          this.$dialog({ message: res.msg })
        }
        this.show = false
      })
    },
    backHome () {
      this.$router.push('/index')
    },
    download () {
      if (this.$store.state.pl === 'ANDROID') {
        AndroidJsBridge.download(window.location.protocol + '//' + window.location.host + this.$img('syd.png'))
      } else if (this.$store.state.pl === 'IOS') {
        window.iosCallHandler('download', window.location.protocol + '//' + window.location.host + this.$img('syd.png'))
      } else {
        var a = document.createElement('a')
        var url = window.location.protocol + '//' + window.location.host + this.$img('syd.png')
        var filename = 'sys.png'
        a.href = url
        a.download = filename
        a.click()
        window.URL.revokeObjextURL(url)
      }
    },
    onConfirm (value) {
      this.value = value.text
      this.form.category = value.value
      this.showPicker = false
    },
    getMerchantCategory () {
      this.$axios.get('/api/merchant_category').then(res => {
        if (res.status === 200) {
          for (let x in res.data) {
            this.columns.push({
              text: res.data[x].name,
              value: res.data[x].id
            })
          }
        }
      })
    },
    uploadfile (file) {
      this.show = true
      this.$upload(file).then(res => {
        this.form[this.formKeys] = res[0]
        this.show = false
      }).catch(_ => {
        this.show = false
      })
    },
    beforeUploadSetKeysCheckBook () {
      this.formKeys = 'check_book'
      return true
    },
    beforeUploadSetKeysLogo () {
      this.formKeys = 'logo'
      return true
    },
    beforeUploadSetKeysIdcardBack () {
      this.formKeys = 'idcard_back'
      return true
    },
    beforeUploadSetKeysIdcardFront () {
      this.formKeys = 'idcard_front'
      return true
    },
    beforeUploadSetKeysHandIdcard () {
      this.formKeys = 'hand_idcard'
      return true
    },
    beforeUploadSetKeysLicense () {
      this.formKeys = 'license'
      return true
    },
    getAuthInfo () {
      this.$axios.get('/api/user/merchant').then(res => {
        if (res.status === 200) {
          if (res.data) {
            this.authStatus = res.data.status
            this.is_pay = res.data.order.paid
            this.orderid = res.data.order.order_id
            this.total_price = res.data.order.total_price
            this.showLoad = false
          }
        }
      })
    },
    preview (img) {
      this.previewimg = [img]
      this.previewShow = true
    },
    toRule (url) {
      this.$router.push(`/clause?code=${url}`)
    },
    toPay () {
      this.$router.push(`/CreateOrder?wxid=${this.orderid}&price=${this.total_price}`)
    }
  },
  created () {
    this.areaList = area
    if (this.$store.state.pl === 'H5') {
      this.isApp = false
    } else {
      this.isApp = true
    }
    this.getMerchantCategory()
    this.getAuthInfo()
  }
}
</script>

<style lang="scss">
@import './index.scss';
</style>
